import { PageContainer, ProDescriptions } from "@ant-design/pro-components";
import { FC, useEffect, useRef, useState } from "react";
import { history, useParams } from "umi";
import {
  Card,
  QRCode,
  Tabs,
  TabsProps,
  message,
  Spin,
  Tag,
  Modal,
  Button,
  Divider,
} from "antd";
import styles from "./index.less";
import Https from "@/utils/Https";
import { orderStataus } from "./configFile";
import { BtnList } from "./configFile";
import Countdown from "./cutDown";
import { CheckCircleFilled, ScanOutlined } from "@ant-design/icons";
const ConfirmOrder: FC<any> = () => {
  let { id, type } = useParams();
  const [modal, contextHolder] = Modal.useModal();
  var timeCurrent = useRef(null);
  // 使用useRef钩子来存储定时器ID
  const [activeKey, setActiveKey] = useState("1");
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const [wxQrCode, setWxQrCode] = useState("");
  const [isCountEnd, setIsCountEnd] = useState(false);
  const [wxCode, setWxCode] = useState(0);
  const [codeLoading, setCodeLoading] = useState(false);
  const [orderInfo, setOrderInfo] = useState<any>({});
  //获取订单详情
  const getDetails = async (id) => {
    setLoading(true);
    let res = await Https.get("/band/package/orderDetail", { id }, true);
    setLoading(false);
    if (res.code == 200) {
      setOrderInfo(res.data);
      if (res.data.orderStatus == "0" && activeKey == "1") {
        getWxCode(id);
      }
    } else {
      setOrderInfo({});
      message.error(res.msg);
    }
  };
  //获取微信支付二维码
  const getWxCode = async (id) => {
    setCodeLoading(true);
    let res = await Https.get("/band/package/toWxQrPay", { id }, true);
    setCodeLoading(false);
    if (res.code == 200) {
      setWxQrCode(res.data);
      setWxCode(3600);
      setIsCountEnd(false);
      getOrderStatus(id);
    } else {
      setWxQrCode("");
      setWxCode(0);
      setIsCountEnd(false);
      message.error(res.msg);
    }
  };
  //获取订单状态
  const getOrderStatus = (id) => {
    timeCurrent.current = setInterval(async () => {
      let res = await Https.get(
        "/band/package/getOrderStatusById",
        { id },
        true
      );
      console.log(res, "-res");
      if (res.code == 200 && res.data == "1") {
        clearInterval(timeCurrent.current);
        modal.confirm({
          title: (
            <div>
              <CheckCircleFilled
                style={{
                  color: "#52c41a",
                  fontSize: "18px",
                  marginRight: "5px",
                }}
              />
              支付成功
            </div>
          ),
          icon: null,
          content: "已支付成功,服务已生效",
          okText: "查看订单详情",
          cancelText: "返回到订单列表",
          onCancel: () => {
            history.push("/brand/information");
          },
          onOk: () => {
            getDetails(id);
          },
        });
      }
    }, 6000);
  };
  const items: TabsProps["items"] = [
    {
      key: "1",
      label: "微信支付",
    },
    {
      key: "2",
      label: "支付宝支付",
    },
  ];
  const goPay = async () => {
    let res = await Https.get("/band/package/toAliPay", { id }, true);
    if (res.code) {
      message.error(res.msg);
    } else {
      const div = document.createElement("div");
      div.innerHTML = res; // html code
      document.body.appendChild(div);
      document.forms.alipaysubmit.setAttribute("target", "_blank");
      document.forms.alipaysubmit.submit();
      setOpen(true);
    }
  };
  useEffect(() => {
    if (id) {
      getDetails(id);
    }
    return () => {
      clearInterval(timeCurrent.current);
    };
  }, []);
  return (
    <Spin spinning={loading}>
      {orderInfo.id && (
        <PageContainer
          title="确认订单"
          onBack={() => {
            history.push("/brand/information", { type });
          }}
          className={styles.ConfirmOrderClass}
        >
          <Card>
            <div className={styles.orderHeader}>
              <div className={styles.orderHeaderLeft}>
                <div className={styles.Header_icon}>
                  <img src={orderStataus[orderInfo.orderStatus].icon} alt="" />
                </div>
                <div className={styles.Header_text}>
                  <div
                    className={styles.header_status}
                    style={{ color: orderStataus[orderInfo.orderStatus].color }}
                  >
                    {orderStataus[orderInfo.orderStatus].text}
                  </div>
                  <span>订单号：{id}</span>
                </div>
              </div>
              <div className={styles.orderHeaderRight}>
                <div className={styles.Header_money}>
                  应付金额：
                  <span style={{ color: "red" }}>
                    ¥{Number(orderInfo.orderAmount / 100)}
                  </span>
                </div>
                {orderInfo.orderStatus == "0" && (
                  <div className={styles.Header_time}>
                    剩余支付时间
                    <a style={{ color: "red", margin: "0 5px" }}>
                      {orderInfo.expire > 0 && (
                        <Countdown
                          count={orderInfo.expire}
                          onEnd={() => {
                            Modal.info({
                              title: "提示消息",
                              icon: null,
                              content: "订单已失效,请重新下单",
                              onOk() {
                                history.push("/brand/information");
                              },
                            });
                          }}
                        />
                      )}
                    </a>
                    , 否则订单将自动失效
                  </div>
                )}
              </div>
            </div>
          </Card>
          <Card title="产品信息">
            <ProDescriptions layout="vertical">
              <ProDescriptions.Item label="品牌名称">
                {orderInfo.brandName}
              </ProDescriptions.Item>
              <ProDescriptions.Item label="套餐名称">
                {orderInfo.packageName}
              </ProDescriptions.Item>
              <ProDescriptions.Item label="失效时间" valueType={"dateTime"}>
                {orderInfo.validityDate}
              </ProDescriptions.Item>
              <ProDescriptions.Item label="加购场馆数量">
                {orderInfo.venueNum}个
              </ProDescriptions.Item>
              <ProDescriptions.Item label="套餐原价">
                ¥{Number(orderInfo.originalAmount / 100)}
              </ProDescriptions.Item>
            </ProDescriptions>
          </Card>
          <Card title="订单信息">
            <ProDescriptions layout="vertical">
              <ProDescriptions.Item label="订单类型">
                {BtnList[orderInfo.orderType]}
              </ProDescriptions.Item>
              <ProDescriptions.Item label="下单时间" valueType={"dateTime"}>
                {orderInfo.buyTime}
              </ProDescriptions.Item>
              {(orderInfo.orderStatus == "1" ||
                orderInfo.orderStatus == "4" ||
                orderInfo.orderStatus == "5") && (
                <>
                  <ProDescriptions.Item label="生效时间" valueType={"dateTime"}>
                    {orderInfo.buyTime}
                  </ProDescriptions.Item>
                  <ProDescriptions.Item label="失效时间" valueType={"dateTime"}>
                    {orderInfo.validityDate}
                  </ProDescriptions.Item>
                  <ProDescriptions.Item label="订单状态">
                    <Tag color={orderStataus[orderInfo.orderStatus].color}>
                      {orderStataus[orderInfo.orderStatus].text}
                    </Tag>
                  </ProDescriptions.Item>
                </>
              )}
            </ProDescriptions>
          </Card>
          {(orderInfo.orderStatus == "1" ||
            orderInfo.orderStatus == "4" ||
            orderInfo.orderStatus == "5") && (
            <Card title="支付信息">
              <ProDescriptions layout="vertical">
                <ProDescriptions.Item label="支付单号">
                  {orderInfo.id}
                </ProDescriptions.Item>
                <ProDescriptions.Item
                  label="支付方式"
                  valueEnum={{
                    1: { text: "微信" },
                    2: { text: "支付宝" },
                  }}
                >
                  {orderInfo.payMode}
                </ProDescriptions.Item>
                <ProDescriptions.Item label="支付时间" valueType={"dateTime"}>
                  {orderInfo.payTime}
                </ProDescriptions.Item>
              </ProDescriptions>
            </Card>
          )}
          {orderInfo.orderStatus == "0" && (
            <Card>
              <Tabs
                activeKey={activeKey}
                items={items}
                onChange={(e) => {
                  clearInterval(timeCurrent.current);
                  if (e == "1") {
                    getWxCode(id);
                  }
                  setActiveKey(e);
                }}
              />
              {activeKey == "1" && (
                <div>
                  <div style={{ margin: "10px 0" }}>
                    距离二维码过期还剩
                    <span style={{ color: "red", margin: "0 5px" }}>
                      {wxCode > 0 && wxQrCode && !codeLoading ? (
                        <Countdown
                          count={wxCode}
                          onEnd={() => {
                            setIsCountEnd(true);
                          }}
                        />
                      ) : (
                        "00:00:00"
                      )}
                    </span>
                    秒,过期后请
                    <a
                      style={{
                        margin: "0 5px",
                        pointerEvents: !isCountEnd ? "none" : "",
                        color: !isCountEnd ? "#666666" : "",
                      }}
                      onClick={() => {
                        getWxCode(id);
                      }}
                    >
                      刷新
                    </a>
                    重新获取二维码
                  </div>
                  <div className={styles.wxCodeBox}>
                    <Spin spinning={codeLoading}>
                      <QRCode value={wxQrCode} size={200} />
                      {isCountEnd && (
                        <div className={styles.wxCodeToast}>
                          <div
                            className={styles.wxCodeBtn}
                            onClick={() => {
                              getWxCode(id);
                            }}
                          >
                            点击刷新二维码
                          </div>
                        </div>
                      )}
                    </Spin>
                  </div>
                  <div className={styles.wxScanIcon}>
                    <ScanOutlined />
                    <span className={styles.tips}>请使用微信扫二维码支付</span>
                  </div>
                </div>
              )}
              {activeKey == "2" && (
                <div>
                  <div>欢迎使用支付宝支付，请点击生成二维码进行支付~</div>
                  <Button
                    type="primary"
                    onClick={() => {
                      goPay();
                    }}
                    style={{ marginTop: "10px" }}
                  >
                    点击去支付
                  </Button>
                </div>
              )}
            </Card>
          )}
          <Modal
            title=""
            open={open}
            closeIcon={false}
            footer={null}
            maskClosable={false}
            wrapClassName={styles.payBox}
            onCancel={() => {
              setOpen(false);
            }}
          >
            <div className={styles.payBtn}>
              支付成功
              <br />
              <a
                onClick={async () => {
                  let res = await Https.get(
                    "/band/package/getOrderStatusById",
                    { id },
                    true
                  );
                  if (res.code == 200 && res.data == "1") {
                    getDetails(id);
                    setOpen(false);
                  } else {
                    message.warning(res.msg);
                  }
                }}
              >
                查看订单详情{">>"}
              </a>
            </div>
            <Divider />
            <div className={styles.payBtn}>
              支付失败 <br /> <span>立即反馈遇到的问题{">>"}</span>
            </div>
            <Divider />
            <div
              onClick={() => {
                setOpen(false);
              }}
            >
              <a>返回选择其他支付方式{">>"}</a>
            </div>
          </Modal>
        </PageContainer>
      )}
      {contextHolder}
    </Spin>
  );
};
export default ConfirmOrder;
